package com.yc.framework.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Date;

import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.util.WebUtils;


/**
 * <p>
 * </p>
 *
  * @since V1.0
 */
public class FileUploadUtils {
    private static final Logger logger = LoggerFactory.getLogger(FileUploadUtils.class);
    private static final String UPLOAD_PATH = "files/upload/";

    public FileUploadUtils() {
    }

    public static String getUploadFileFullSavePath(ServletContext context) throws FileNotFoundException {
        return getServletContextPath(context) + getUploadFileSavePath(context);
    }

    public static String getUploadFileSavePath(ServletContext context) throws FileNotFoundException {
        String uploadPath = UPLOAD_PATH;
        String uploadDatePath = DateTools.getYYYY_MM_DD(new Date());

        String uploadFileSavePath = uploadPath + uploadDatePath;
        File dir = new File(getServletContextPath(context), uploadFileSavePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        return uploadFileSavePath;
    }

    public static String getServletContextPath(ServletContext context) throws FileNotFoundException {
        String ctxPath = WebUtils.getRealPath(context, File.separator);
        logger.debug("...servletContext.getRealPath({}):={}", File.separator, ctxPath);
        if (!ctxPath.endsWith(File.separator)) {
            ctxPath = ctxPath + File.separator;
        }

        return ctxPath;
    }
}
